package common

import (
	"time"
	"phoenix/gin_web/model"
	"github.com/golang-jwt/jwt/v4"
)

var jwtKey = []byte("gin_web_secret")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func ReleaseToken(user *model.User) (string, error) {
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt: time.Now().Unix(),
			Issuer: "bobola",
			Subject: "user token",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

func ParseToken(t string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	token, err :=  jwt.ParseWithClaims(t, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	}) 

	return token, claims, err	
}	